package org.framework.helper;

import org.framework.annotation.Inject;
import org.framework.utils.ArrayUtil;
import org.framework.utils.CollectionUtil;
import org.framework.utils.ReflectUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * ioc 控制反转
 * @Author xuelongjiang
 */
public final class IocHelper {

    static{

        Map<Class<?>,Object> beanMap = BeanHelper.getBeanMap();
        if(CollectionUtil.isNotEmpty(beanMap)){
            for(Map.Entry<Class<?>,Object> beanEntry : beanMap.entrySet()){
                    Class<?> beanClass = beanEntry.getKey();
                    Object beanInstance = beanEntry.getValue();
                    Field [] fields = beanClass.getFields();
                    if(ArrayUtil.isNotEmpty(fields)){
                        for(Field beanField : fields){
                            if(beanField.isAnnotationPresent(Inject.class)){
                                Class<?> fieldClass = beanField.getType();
                                Object beanFieldInstance = BeanHelper.getBean(fieldClass);
                                if(beanFieldInstance != null){
                                    ReflectUtil.setFile(beanInstance,beanField,beanFieldInstance);
                                }
                            }
                        }
                    }
            }
        }
    }
}
